package com.ari.actions;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.devicemantra.coordinate.dao.HibernateUtil;
import com.devicemantra.coordinate.dao.Settings;

public class SettingsAction {

	private String ipAddress;
	private String portNumber;
	private String username;
	private String password;
	private String outCome;

	static final Logger logger = Logger.getLogger(SettingsAction.class);

	public SettingsAction() {
		ipAddress = "";
		portNumber = "";
		username = "";
		password = "";
	}

	public String execute() {
		logger.info("*********************" + this);

		try {

			logger.info("Sleeping for 4 seconds");
			Thread.sleep(1000);
		} catch (final InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if ("".equals(ipAddress)) {
			return "view";
		}

		outCome = "Successfully done operation";
		final Settings settings = new Settings();
		Transaction transaction = null;
		try {
			final Session session = HibernateUtil.getSession();
			settings.setEppdIp(ipAddress);
			settings.setEppdPort(portNumber);
			settings.setEppdUsername(username);
			settings.setEppdPassword(password);
			transaction = session.beginTransaction();
			session.save(settings);
			transaction.commit();
		} catch (final HibernateException e) {
			System.out.println("Rolling back");
			outCome = "Failed to save operation";
			transaction.rollback();
			e.printStackTrace();
		}
		return "outcome";
	}

	public void validate() {
		if ((ipAddress.length() > 0) && (portNumber.length() > 0)
				&& (username.length() > 0) && password.length() > 0) {

		}
	}

	public String getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(final String ipAddress) {
		logger.info("Setter for ip address called now");
		this.ipAddress = ipAddress;
	}

	public String getPortNumber() {
		return portNumber;
	}

	public void setPortNumber(final String portNumber) {
		logger.info("Setter for portnumber called now");
		this.portNumber = portNumber;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(final String username) {
		logger.info("Setter for username called now");
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(final String password) {
		logger.info("Setter for password called now");
		this.password = password;
	}

	public void setOutCome(final String outCome) {
		this.outCome = outCome;
	}

	public String getOutCome() {
		return outCome;
	}

	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();
		builder.append("IP Address is :" + ipAddress + " ");
		builder.append("Port is :" + portNumber + " ");
		builder.append("Username is :" + username + " ");
		builder.append("Password is :" + password + " ");
		return builder.toString();

	}
}
